﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LibNiconico.NiconicoApi.Extentions
{
    /// <summary>
    /// DateTime拡張
    /// </summary>
    public static class DateTimeExtention
    {
        /// <summary>
        /// Unix基準時間
        /// </summary>
        public readonly static DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);


        /// <summary>
        /// 基準開始時間
        /// </summary>
        public static DateTime Epoch
        {
            get { return UnixEpoch; }
        }

        /// <summary>
        /// local時間をUnix時間に変換
        /// </summary>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        public static long ToUnixTime(DateTime dateTime)
        {
            if (dateTime.Kind != DateTimeKind.Local)
                dateTime = dateTime.ToUniversalTime();

            return (long)dateTime.Subtract(UnixEpoch).TotalSeconds;
        }

        /// <summary>
        /// Unix時間からlocal時間に変換
        /// </summary>
        /// <param name="unixTime"></param>
        /// <returns></returns>
        public static DateTime FromUnixTime(long unixTime)
        {
            return _fromUnixTime(unixTime, DateTimeKind.Local).ToLocalTime();
        }

        private static DateTime _fromUnixTime(long unixTime, DateTimeKind kind)
        {
            if (kind == DateTimeKind.Utc)
            {
                return UnixEpoch.AddSeconds(unixTime).ToUniversalTime();
            }
            else if (kind == DateTimeKind.Local)
            {
                return UnixEpoch.AddSeconds(unixTime).ToLocalTime();
            }
            else
            {
                return default(DateTime);
            }
        }
    }
}
